import { myRequest } from '@/utils/request.js';

const handleMyRequestSuccess = (response) => {
    if (response && response.code === 1000) {
        return {
            success: true,
            data: response.data,
            message: response.msg
        };
    } else {
        return {
            success: false,
            data: response.data || null,
            message: response.msg || '服务器返回未知错误'
        };
    }
};


const handleMyRequestError = (err) => {
    console.error('API 请求错误:', err);
    let message = '网络请求失败';
    if (err.statusCode) {
        message = `请求失败，状态码: ${err.statusCode}`;
    } else if (err.errMsg) {
        message = `请求错误: ${err.errMsg}`;
    }
    return {
        success: false,
        message: message
    };
};

const courseService = {


    createCourse(courseData, imageFile) {
        const formData = new FormData();
        formData.append('course', new Blob([JSON.stringify(courseData)], { type: 'application/json' }));
        if (imageFile) {
            formData.append('imageFile', imageFile);
        }

        return new Promise((resolve, reject) => {
            myRequest.formRequest({
                url: 'courses',
                method: 'POST',
                data: formData,
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '课程创建失败' });
                    }
                },
                error: reject
            });
        });
    },


    getCourseById(courseId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}`,
                method: 'GET',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data });
                    } else {
                        resolve({ success: false, message: response.msg || '获取课程详情失败' });
                    }
                },
                error: reject
            });
        });
    },


    getCourseList(params) {
        return new Promise((resolve, reject) => {
            const { teacherId, page = 1, size = 10 } = params;
            const url = `courses?teacherId=${teacherId}&page=${page}&size=${size}`;
            myRequest.request({
                url: url,
                method: 'GET',
                success: (response) => resolve(handleMyRequestSuccess(response)),
                error: (err) => reject(handleMyRequestError(err))
            });
        });
    },

    getSelectedCoursesByUserId(userId, { page = 1, size = 10 }) {
        return new Promise((resolve, reject) => {
            const url = `courses/selections/student/${userId}?page=${page}&size=${size}`;

            myRequest.request({
                url: url,
                method: 'GET',
                success: (response) => {
                    // 【修复】不再对后端返回的数据进行任何转换。
                    // 直接将原始的 response 传递给辅助函数处理。
                    // 后端返回的 snake_case 字段 (e.g., progress_percent) 将直接传递给 Vue 组件。
                    resolve(handleMyRequestSuccess(response));
                },
                error: (err) => {
                    reject(handleMyRequestError(err));
                }
            });
        });
    },



    updateCourse(courseId, courseData) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}`,
                method: 'PUT',
                data: courseData,
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '课程更新失败' });
                    }
                },
                error: reject
            });
        });
    },


    deleteCourse(courseId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}`,
                method: 'DELETE',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '课程删除失败' });
                    }
                },
                error: reject
            });
        });
    },



    linkResourceToCourse(courseId, resourceId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/resources`,
                method: 'POST',
                data: { resourceId: resourceId },
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '资源关联失败' });
                    }
                },
                error: reject
            });
        });
    },

    unlinkResourceFromCourse(courseId, resourceId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/resources/${resourceId}`,
                method: 'DELETE',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '解除关联失败' });
                    }
                },
                error: reject
            });
        });
    },

    getCourseResources(courseId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/resources`,
                method: 'GET',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data });
                    } else {
                        resolve({ success: false, message: response.msg || '获取课程资源列表失败' });
                    }
                },
                error: reject
            });
        });
    },

    selectCourse(courseId, userId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/selections`,
                method: 'POST',
                data: { userId: userId },
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '选课失败' });
                    }
                },
                error: reject
            });
        });
    },

    unselectCourse(courseId, userId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/selections?userId=${userId}`,
                method: 'DELETE',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '取消选课失败' });
                    }
                },
                error: reject
            });
        });
    },

    getCourseSelections(courseId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/selections`,
                method: 'GET',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data });
                    } else {
                        resolve({ success: false, message: response.msg || '获取选课列表失败' });
                    }
                },
                error: reject
            });
        });
    },

    /**
     * 搜索课程.
     * @param {object} params - 查询参数, 例如 { courseName: 'Vue', teacherName: '张三', page: 1, size: 10 }.
     * @returns {Promise}
     */
    searchCourses(params) {
        const query = new URLSearchParams(params).toString();
        const urlWithParams = `courses?${query}`;
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: urlWithParams,
                method: 'GET',
                success: (response) => {
                    if (response && response.code === 1000) {
                        resolve({ success: true, data: response.data, message: response.msg });
                    } else {
                        resolve({ success: false, message: response.msg || '搜索课程失败' });
                    }
                },
                error: reject
            });
        });
    },


        getNextChapterNumber(courseId) {
            return new Promise((resolve, reject) => {
                myRequest.request({
                    url: `courses/${courseId}/resources/nextChapter`, // 确保URL正确
                    method: 'GET',
                    success: (response) => {
                        if (response && response.code === 1000) {
                            resolve({ success: true, data: response.data });
                        } else {
                            resolve({ success: false, message: response.msg || '获取下一个章节号失败' });
                        }
                    },
                    error: reject
                });
            });
        },

        addResourceToChapter(courseId, payload) { // 确保这个方法也存在
            return new Promise((resolve, reject) => {
                myRequest.request({
                    url: `courses/${courseId}/resources/withChapter`, // 确保URL正确
                    method: 'POST',
                    data: payload,
                    success: (response) => {
                        if (response && response.code === 1000) {
                            resolve({ success: true, data: response.data, message: response.msg });
                        } else {
                            resolve({ success: false, message: response.msg || '添加资源到章节失败' });
                        }
                    },
                    error: reject
                });
            });
        },

    getCourseFullResources(courseId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/${courseId}/full-resources`,
                method: 'GET',
                success: (response) => {
                    resolve(handleMyRequestSuccess(response));
                },
                error: (err) => {
                    reject(handleMyRequestError(err));
                }
            });
        });
    },

    countCoursesByTeacherId(teacherId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/count/teacher/${teacherId}`,
                method: 'GET',
                success: (response) => resolve(handleMyRequestSuccess(response)),
                error: (err) => reject(handleMyRequestError(err))
            });
        });
    },

    countSelectedCoursesByStudentId(studentId) {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: `courses/count/student/${studentId}`,
                method: 'GET',
                success: (response) => resolve(handleMyRequestSuccess(response)),
                error: (err) => reject(handleMyRequestError(err))
            });
        });
    },

};

export default courseService;
